package com.aisino.api.exception;

import com.aisino.api.model.DrugResponseBase;
import com.aisino.api.model.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import jakarta.servlet.http.HttpServletRequest;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 处理所有未捕获的异常
     * @param request HttpServletRequest对象
     * @param e 异常对象
     * @return 统一的错误响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK) // 改为200状态码
    @ResponseBody
    public DrugResponseBase handleException(HttpServletRequest request, Exception e) {
        logger.error("请求 {} 出现未处理的异常: ", request.getRequestURI(), e);
        
        String reqId = extractReqIdFromRequest(request);


        // 返回统一的错误响应
        return new DrugResponseBase(
            ResultCode.FAILURE.getCode(), 
            "操作失败: 请联系客服" ,
            reqId
        );
    }


    private String extractReqIdFromRequest(HttpServletRequest request) {
        try {
            // 尝试从请求参数中获取reqId
            String reqId = request.getParameter("reqId");
            if (reqId != null && !reqId.isEmpty()) {
                return reqId;
            }

            // 尝试从请求体中获取reqId（仅适用于POST请求）
            String contentType = request.getContentType();
            if (contentType != null && contentType.contains("application/json")) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                int totalBytesRead = 0;
                int maxRequestSize = 10 * 1024 * 1024; // 10MB
                StringBuilder requestBody = new StringBuilder();

                try (InputStream inputStream = request.getInputStream()) {
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        totalBytesRead += bytesRead;
                        if (totalBytesRead > maxRequestSize) {
                            throw new IOException("Request body exceeds maximum size limit");
                        }
                        requestBody.append(new String(buffer, 0, bytesRead, StandardCharsets.UTF_8));
                    }
                }

                if (requestBody.length() > 0) {
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonNode = mapper.readTree(requestBody.toString());
                    if (jsonNode.has("reqId")) {
                        return jsonNode.get("reqId").asText();
                    }
                }
            }
        } catch (IOException | RuntimeException e) {
            logger.warn("从请求中提取reqId时出错: ", e);
        }

        return null;
    }
}